package disjunction.extensions.view
{
	import disjunction.core.*;
	import disjunction.core.IView;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;

	/**
	 * Wraps a DisplayObjectContainer for use as an entity list based view within the framework.
	 *
	 * @author Nick Wiggill
	 */
	
	public class DisplayObjectEntityListView extends EntityListView
	{		
		public override function add(entity:*):void
		{
			//will throw cast error if element in entity view list is incorrect type
			var entityView:EntityView = _entitiesByModel[entity];
			entityView.model = entity;
			if (entityView == null)
			{
				//creator is non optional, so we will fail with a NPE if the creator is null
				entityView = entityCreator.create(entity); //createFor()?
				
				//add to own lists (entities)
				_entities.push(entityView);
				_entitiesByModel[entity] = entityView;
				
				//add to rendering system list (displayobjects)
				context.addChild((entityView as DisplayObjectEntity2D).displayObject);
			}
		}
		
		/** Removes an entity from the view. */
		public override function remove(entity:*):void
		{
			var entityView:EntityView = _entitiesByModel[entity];
			entityView.model = null;
			if (entityView != null)
			{				
				//remove from rendering system list (displayobjects)
				context.removeChild((entityView as DisplayObjectEntity2D).displayObject);	
				
				//remove from own lists (entities)
				_entities.splice(_entities.lastIndexOf(entityView), 1);
				delete _entitiesByModel[entity];
				
				//destroy the object
				if (entityDestroyer) //since this optional, check if it applies
				{		
					entityDestroyer.destroy(entity); //model? view? should be destroyFor()?
				}
			}
		}
	}
}